package com.kolon.business.login.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jdom.Document;
import org.jdom.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.kolon.business.login.dao.LoginDao;
import com.kolon.framework.constant.Constant;
import com.kolon.framework.interfaces.SimpleController;
import com.kolon.framework.util.ComUtil;
import com.kolon.framework.util.DateUtil;
import com.kolon.framework.util.MsgUtil;

/**
 * 웹 로그인 처리 컨트롤러
 * @author stone
 */
@Controller("com.kolon.business.login.controller.WebLoginController")
public class WebLoginController implements SimpleController {

	@Resource(name="com.kolon.business.login.dao.LoginDaoImpl")
	private LoginDao loginDao;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="/business/login/webLogin.do")
	public ModelAndView controller(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 도메인
		String url = MsgUtil.getMessage("auth.url");
		String cxu = MsgUtil.getMessage("concise.xml.url");
		// 아이디, 암호 파라미터
		String id = ComUtil.getNullCheck(request.getParameter("userId"));
		String pw = ComUtil.getNullCheck(request.getParameter("userPw"));
		String qry = ComUtil.getNullCheck(request.getParameter("qry"));
		cxu = cxu + id;
		// 리턴
		int responseCode = ComUtil.getResponseCode(url, id, pw);
		// 인증 성공 시 세션 생성
		HttpSession session = request.getSession();
		ModelAndView modelAndView = new ModelAndView();
		if (responseCode == 200) {
			Map map = new HashMap();
			map.put("userId", id);
			map.put("userPw", pw);
			map.put("conciseGrade", "");
			map.putAll(loginDao.getMap(map));
			// 콘사이스 권한 정보 리턴 (Grade -1일시 권한없음, Grade A,B,C 권한 있음)
			Document doc = ComUtil.getDocument(cxu);
			if (doc != null) {
				Element element = doc.getRootElement();
				List xmlList = element.getChildren("UserInfo");
				Iterator itXml = xmlList.iterator();
				if (itXml.hasNext()) {
					Element el = (Element)itXml.next();
					String grade = el.getChild("Grade").getText();
					if (!"-1".equals(grade))
						map.put("conciseGrade", grade);
				}
			}
			// 세션생성, 세션 시간 60분
			session.setAttribute(Constant.SESSION_USER_INFO, map);
			session.setMaxInactiveInterval(60000);
			// 쿠키 생성
			Cookie cId = new Cookie("cId", id);
			Cookie cPw = new Cookie("cPw", pw);
			cId.setMaxAge(6000);
			cPw.setMaxAge(6000);
			cId.setPath("/");
			cPw.setPath("/");
			response.addCookie(cId);
			response.addCookie(cPw);
			// 로그 등록
			map.put("connDate", DateUtil.getYearStr()+DateUtil.getMonthStr());
			loginDao.insertCntLog(map);
			//로그인 시 처리되는 루틴
			System.out.println("TEST :"+qry);
			if ("".equals(qry))
				
				modelAndView.setViewName("redirect:/business/mKolonNews/mKolonNewsList.do");
				//modelAndView.setViewName("redirect:/business/mVolunteer/mVolunteerList.do");
			else
			modelAndView.setViewName("redirect:"+qry);
		} else {
			session.invalidate();
			modelAndView.setViewName("redirect:/business/login/webLoginForm.do");
			modelAndView.addObject("qry", qry);
		}
		return modelAndView;
	}

}
